/*
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * This file is a part of the CANN Open Software.
 * Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 */

#include "../../common/data_utils.h"
#include "kernel_tiling/kernel_tiling.h"
#include "tiling/platform/platform_ascendc.h"
#include "./op_host/matmul_l2_cache_custom_tiling.h"

#ifndef ASCENDC_CPU_DEBUG
#include "acl/acl.h"
extern void matmul_l2_cache_custom_do(uint32_t coreDim, void* stream,
    uint8_t* a, uint8_t* b, uint8_t* bias, uint8_t* c, uint8_t* workspace, uint8_t* tiling);
#else
#include "tikicpulib.h"
extern "C" void matmul_l2_cache_custom(
    uint8_t* a, uint8_t* b, uint8_t* bias, uint8_t* c, uint8_t* workspace, uint8_t* tiling);
#endif

int64_t CompareResult(void* outputData, const int64_t outSize)
{
    void* goldenData;
#ifdef ASCENDC_CPU_DEBUG
    goldenData = (uint8_t*)AscendC::GmAlloc(outSize);
#else
    CHECK_ACL(aclrtMallocHost((void**)(&goldenData), outSize));
#endif
    size_t goldenSize = outSize;
    bool ret = ReadFile("../output/golden_c.bin", goldenSize, goldenData, goldenSize);
    if (ret) {
        printf("ReadFile golden success!\n");
    } else {
#ifdef ASCENDC_CPU_DEBUG
        AscendC::GmFree((void*)goldenData);
#else
        CHECK_ACL(aclrtFreeHost(goldenData));
#endif
        return -1;
    }
    constexpr float EPS = 1e-3;
    int64_t wrongNum = 0;
    int64_t maxPrintNums = 10;
    for (int i = 0; i < outSize / sizeof(float); i++) {
        float a = ((float*)outputData)[i];
        float b = ((float*)goldenData)[i];
        float ae = std::abs(a - b);
        float re = ae / abs(b);
        if (ae > EPS && re > EPS) {
            printf("CompareResult index %d failed output is %lf, golden is %lf\n", i, a, b);
            wrongNum++;
        }
        if (wrongNum > maxPrintNums) {
            break;
        }
    }
#ifdef ASCENDC_CPU_DEBUG
    AscendC::GmFree((void*)goldenData);
#else
    CHECK_ACL(aclrtFreeHost(goldenData));
#endif
    return wrongNum;
}

int32_t main(int32_t argc, char* argv[])
{
    const char* socVersion = SOC_VERSION;
    auto ascendcPlatform = platform_ascendc::PlatformAscendCManager::GetInstance(socVersion);
    auto aivCoreNum = ascendcPlatform->GetCoreNum();
    auto aicCoreNum = aivCoreNum / 2; // aic : aiv = 1 : 2

    optiling::TestcaseParams caseParams = {aicCoreNum, 30720, 1024, 1024, true, 2};

    uint32_t blockDim = caseParams.blockDim;
    uint32_t M = caseParams.m;
    uint32_t N = caseParams.n;
    uint32_t K = caseParams.k;
    bool isBias = caseParams.isBias;

    size_t aFileSize = static_cast<size_t>(sizeof(float) * M * K);
    size_t bFileSize = static_cast<size_t>(sizeof(float) * K * N);
    size_t biasFileSize = static_cast<size_t>(sizeof(float) * N);
    size_t cFileSize = static_cast<size_t>(sizeof(float) * M * N);
    size_t userWorkspaceSize = 0;
    size_t systemWorkspaceSize = static_cast<size_t>(ascendcPlatform->GetLibApiWorkSpaceSize());
    size_t workspaceSize = userWorkspaceSize + systemWorkspaceSize;
    size_t tilingFileSize = sizeof(TCubeTiling);
    int64_t wrongNum = -1;

#ifdef ASCENDC_CPU_DEBUG
    uint8_t* a = (uint8_t *)AscendC::GmAlloc(aFileSize);
    uint8_t* b = (uint8_t *)AscendC::GmAlloc(bFileSize);
    uint8_t* bias = (uint8_t *)AscendC::GmAlloc(biasFileSize);
    uint8_t* c = (uint8_t *)AscendC::GmAlloc(cFileSize);
    uint8_t* workspace = (uint8_t *)AscendC::GmAlloc(workspaceSize);
    uint8_t* tiling = (uint8_t *)AscendC::GmAlloc(tilingFileSize);

    ReadFile("../input/a_gm.bin", aFileSize, a, aFileSize);
    ReadFile("../input/b_gm.bin", bFileSize, b, bFileSize);
    ReadFile("../input/bias_gm.bin", biasFileSize, bias, biasFileSize);

    optiling::GenerateTiling(socVersion, caseParams, tiling);
    memcpy_s(tiling, tilingFileSize, tiling, tilingFileSize);

    ICPU_RUN_KF(matmul_l2_cache_custom, blockDim, a, b, bias, c, workspace, tiling);

    WriteFile("../output/output.bin", c, cFileSize);

    wrongNum = CompareResult(c, cFileSize);

    AscendC::GmFree((void*)a);
    AscendC::GmFree((void*)b);
    AscendC::GmFree((void*)bias);
    AscendC::GmFree((void*)c);
    AscendC::GmFree((void*)workspace);
    AscendC::GmFree((void*)tiling);
#else
    CHECK_ACL(aclInit(nullptr));
    aclrtContext context;
    int32_t deviceId = 0;
    CHECK_ACL(aclrtSetDevice(deviceId));
    CHECK_ACL(aclrtCreateContext(&context, deviceId));
    aclrtStream stream = nullptr;
    CHECK_ACL(aclrtCreateStream(&stream));

    uint8_t* aHost;
    uint8_t* aDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&aHost), aFileSize));
    CHECK_ACL(aclrtMalloc((void **)&aDevice, aFileSize, ACL_MEM_MALLOC_HUGE_FIRST));
    ReadFile("../input/a_gm.bin", aFileSize, aHost, aFileSize);
    CHECK_ACL(aclrtMemcpy(aDevice, aFileSize, aHost, aFileSize, ACL_MEMCPY_HOST_TO_DEVICE));

    uint8_t* bHost;
    uint8_t* bDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&bHost), bFileSize));
    CHECK_ACL(aclrtMalloc((void **)&bDevice, bFileSize, ACL_MEM_MALLOC_HUGE_FIRST));
    ReadFile("../input/b_gm.bin", bFileSize, bHost, bFileSize);
    CHECK_ACL(aclrtMemcpy(bDevice, bFileSize, bHost, bFileSize, ACL_MEMCPY_HOST_TO_DEVICE));

    uint8_t* biasHost;
    uint8_t* biasDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&biasHost), biasFileSize));
    CHECK_ACL(aclrtMalloc((void **)&biasDevice, biasFileSize, ACL_MEM_MALLOC_HUGE_FIRST));
    ReadFile("../input/bias_gm.bin", biasFileSize, biasHost, biasFileSize);
    CHECK_ACL(aclrtMemcpy(biasDevice, biasFileSize, biasHost, biasFileSize, ACL_MEMCPY_HOST_TO_DEVICE));

    uint8_t* workspaceHost;
    uint8_t* workspaceDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&workspaceHost), workspaceSize));
    CHECK_ACL(aclrtMalloc((void **)&workspaceDevice, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST));

    uint8_t* tilingHost;
    uint8_t* tilingDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&tilingHost), tilingFileSize));
    CHECK_ACL(aclrtMalloc((void **)&tilingDevice, tilingFileSize, ACL_MEM_MALLOC_HUGE_FIRST));
    optiling::GenerateTiling(socVersion, caseParams, tilingHost);
    CHECK_ACL(aclrtMemcpy(tilingHost, tilingFileSize, tilingHost, tilingFileSize, ACL_MEMCPY_HOST_TO_HOST));
    CHECK_ACL(aclrtMemcpy(tilingDevice, tilingFileSize, tilingHost, tilingFileSize, ACL_MEMCPY_HOST_TO_DEVICE));

    uint8_t* cHost;
    uint8_t* cDevice;
    CHECK_ACL(aclrtMallocHost((void **)(&cHost), cFileSize));
    CHECK_ACL(aclrtMalloc((void **)&cDevice, cFileSize, ACL_MEM_MALLOC_HUGE_FIRST));

    matmul_l2_cache_custom_do(blockDim, stream, aDevice, bDevice, biasDevice, cDevice, workspaceDevice, tilingDevice);
    CHECK_ACL(aclrtSynchronizeStream(stream));

    CHECK_ACL(aclrtMemcpy(cHost, cFileSize, cDevice, cFileSize, ACL_MEMCPY_DEVICE_TO_HOST));
    WriteFile("../output/output_c.bin", cHost, cFileSize);

    wrongNum = CompareResult(cHost, cFileSize);

    CHECK_ACL(aclrtFree(aDevice));
    CHECK_ACL(aclrtFreeHost(aHost));

    CHECK_ACL(aclrtFree(bDevice));
    CHECK_ACL(aclrtFreeHost(bHost));

    CHECK_ACL(aclrtFree(biasDevice));
    CHECK_ACL(aclrtFreeHost(biasHost));

    CHECK_ACL(aclrtFree(cDevice));
    CHECK_ACL(aclrtFreeHost(cHost));

    CHECK_ACL(aclrtFree(workspaceDevice));
    CHECK_ACL(aclrtFreeHost(workspaceHost));

    CHECK_ACL(aclrtFree(tilingDevice));
    CHECK_ACL(aclrtFreeHost(tilingHost));

    CHECK_ACL(aclrtDestroyStream(stream));
    CHECK_ACL(aclrtDestroyContext(context));
    CHECK_ACL(aclrtResetDevice(deviceId));
    CHECK_ACL(aclFinalize());
#endif
    if (wrongNum != 0) {
        printf("test failed!\n");
    } else {
        printf("test pass!\n");
    }
    return 0;
}